<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class DailyChallenge extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'challenge_key', 'title', 'description', 'difficulty_level', 'reward_points', 'is_active'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_active' => 'boolean',
        'created_at' => 'datetime',
    ];

    /**
     * 用户挑战记录关系
     */
    public function userChallenges()
    {
        return $this->belongsToMany(User::class, 'user_daily_challenges')
                    ->withPivot(['challenge_date', 'is_completed', 'completed_at', 'reward_earned']);
    }

    /**
     * 获取难度等级文本
     */
    public function getDifficultyTextAttribute()
    {
        $levels = [
            1 => '简单',
            2 => '容易',
            3 => '中等',
            4 => '困难',
            5 => '专家'
        ];

        return $levels[$this->difficulty_level] ?? '未知';
    }

    /**
     * 作用域：活跃的挑战
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 作用域：按难度筛选
     */
    public function scopeByDifficulty($query, $difficulty)
    {
        return $query->where('difficulty_level', $difficulty);
    }
}